<template>
  <div class="step-footer">
    <v-card-actions class="justify-end">
      <v-btn :disabled="flag <= minFlag" variant="outlined" @click="handlePrev">
        上一步
      </v-btn>

      <v-btn v-if="flag < maxFlag" color="primary" @click="handleNext">
        下一步
      </v-btn>

      <v-btn v-if="flag === maxFlag" color="primary" @click="handleNext">
        完成
      </v-btn>

      <v-btn variant="text" @click="close">
        取消
      </v-btn>
    </v-card-actions>
  </div>
</template>

<script setup lang="ts">
import { message } from '@/utils/message';

interface Props {
  flag: number;
  minFlag: number;
  maxFlag: number;
  infoData: {
    obj: any;
    baseForm: any;
    tableForm: any[];
  };
}

const props = withDefaults(defineProps<Props>(), {
  flag: 1,
  minFlag: 1,
  maxFlag: 1,
  infoData: () => ({ obj: null, baseForm: null, tableForm: [] })
});

// 关闭
function close() {
  props.infoData.obj?.$emit?.('close');
}

// 上一步
function handlePrev() {
  props.infoData.obj?.$emit?.('change-step', -1);
}

// 下一步
async function handleNext() {
  await verify(() => {
    props.infoData.obj?.$emit?.('change-step', 1, props.infoData.baseForm, props.infoData.tableForm);
  });
}

/**
 * 验证
 * @param callback 回调
 * @returns {Promise<boolean>}
 */
async function verify(callback: () => void): Promise<boolean> {
  // 验证结果
  let ret = false;

  if (!props.infoData.baseForm) {
    message.warning('表信息不可为空');
    return ret;
  }

  if (!props.infoData.tableForm || props.infoData.tableForm.length === 0) {
    message.warning('表结构不可为空');
    return ret;
  }

  // 基础表单验证
  const baseFormEl = props.infoData.obj?.$refs?.['baseFormRef'];
  if (baseFormEl) {
    try {
      ret = await baseFormEl.validate();
    } catch (error) {
      ret = false;
    }
  } else {
    ret = true; // 如果没有基础表单元素，则认为验证通过
  }

  // 表格表单验证（Vuetify 数据表格通常不需要额外验证）
  const tableFormEl = props.infoData.obj?.$refs?.['tableFormRef'];
  if (tableFormEl && ret) {
    try {
      ret = await tableFormEl.validate();
    } catch (error) {
      ret = false;
    }
  }

  if (ret) {
    callback();
  } else {
    message.error('请检查表单数据');
  }

  return ret;
}
</script>

<style lang="scss">
.step-footer {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  padding: 20px 0;
  overflow: hidden;
  border-top: 1px solid rgba(0, 0, 0, 0.12);
  margin-top: 20px;
}
</style>
